package com.roncoo.education.db.service;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.roncoo.education.api.request.NewsCommentRequest;
import com.roncoo.education.api.request.NewsRequest;
import com.roncoo.education.db.dao.NewsCommentDao;
import com.roncoo.education.db.entity.NewsComment;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class NewsCommentService {

    @Resource
    NewsCommentDao newsCommentDao;


    public Map<String,String> saveNewsComment(NewsCommentRequest req){
        NewsComment news = BeanUtil.copyProperties(req,NewsComment.class);
        Long nid = 0l;


        news.setCommentTime(new Date());
        news.setDelFlag(1);
        newsCommentDao.insert(news);
        nid = news.getId();
        Map<String,String> ret = new HashMap<>();
        ret.put("isError", "success");
        ret.put("id", String.valueOf(nid));
        ret.put("code", "1");
        return ret;
    }

    public PageInfo<NewsComment> getCommentPages(NewsRequest req){
        int pageNum = req.getPageNum();
        int pageSize = req.getCount();
        if (req.getPageNum() == null || req.getPageNum() <= 0 || req.getCount() == null) {
            pageNum = 1;
            pageSize = 20;
        }
        NewsComment query = new NewsComment();
        query.setTitle(req.getTitle());
        query.setCategory(req.getCategory());
        query.setNewsId(req.getNewsId());
        query.setDelFlag(1);
        PageHelper.startPage(pageNum, pageSize);
        List<NewsComment> newsList = newsCommentDao.selectNewsCommentList(query);
        return new PageInfo<>(newsList);
    }

    public PageInfo<NewsComment> getCommentIndexPages(NewsRequest req){
        int pageNum = req.getPageNum();
        int pageSize = req.getCount();
        if (req.getPageNum() == null || req.getPageNum() <= 0 || req.getCount() == null) {
            pageNum = 1;
            pageSize = 20;
        }
        NewsComment query = new NewsComment();
        query.setNewsId(req.getId());
        query.setDelFlag(1);
        PageHelper.startPage(pageNum, pageSize);
        List<NewsComment> newsList = newsCommentDao.findByBeanGetAuthor(query);
        return new PageInfo<>(newsList);
    }

    public void setDelFlag(Long id){
        NewsComment comment = newsCommentDao.findById(id);
        if(comment!=null){
            NewsComment update = new NewsComment();
            update.setId(comment.getId());
            update.setDelFlag(0);
            newsCommentDao.updateById(update);
        }
    }
}
